import React, { useState, useEffect, useCallback } from "react";
import { AppPopupLoading, AppPopupRemove, AppPopupModal } from "../../layout/popup";
import http from "../../../lib/ajax";
import QRCode from "qrcode";

const widthCanvas = window.innerWidth - 100;

function PayQr(props) {
  const [qrcode, setqrcode] = useState("");

  useEffect(() => {
    const canvas = document.getElementById("qrcode-canvas");
    if (!canvas) { return;}
    QRCode.toCanvas( canvas, qrcode, { width: widthCanvas },
      function(error) {
        if (error) console.error(error);
      }
    );
    return () => {
      setqrcode('');
    };
  }, [qrcode]);

  useEffect(() => {
    // console.log(props.userChoose);
    setqrcode('');
    return () => {      
    };
  }, [props.userChoose])

  return (
    <>
      <div className="req-qr" onClick={()=> requestPay.bind(null,props,setqrcode)()}>
        {qrcode ? (
          <div className="qrcode-area">
            <canvas id="qrcode-canvas"></canvas>
            <p className="qrcode-text">{qrcode}</p>
          </div>
        ) : (
          <button className="req-qr-btn">请求支付码</button>
        )}
      </div>
    </>
  );
}

const requestPay = (props, setqrcode) => {
  const phone = document.getElementById("regPhoneNumber").value.trim();
  const cName = document.getElementById("cName").value.trim();
  if (!props.userChoose || phone.length !== 11) {
    AppPopupModal("需选择完报名信息");
    setTimeout(() => {
      AppPopupRemove();
    }, 2500);
    return null;
  }
  // console.log(props.userChoose,phone);
  baomingQrimg(props.userChoose, phone, cName, setqrcode);
};

const baomingQrimg = function(userChoose, phone, cName, setqrcode) { // 请求报名
  let param = {
    classesId: userChoose.teacher.classesId,
    phone: phone,
    clientName: cName ? cName : '',
  };
  http("get", "salesman/attend", param, null, false)
    .then(d => {
      // console.log(d);
      if (d.data.code == 0) {
        setqrcode(d.data.data.codeURL);
      }
    })
    .catch(e => {
      console.warn(e);
    });
};

export { PayQr };
